/**
 * Copyright [2019] [LiBo/Alex of copyright liboware@gmail.com ]
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hyts.uuidkey.snowflake;

import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.time.Clock;

/**
 * @project-name:coffice-toolbox
 * @package-name:com.hyts.uuidkey.snowflake
 * @author:LiBo/Alex
 * @create-date:2019-10-31 22:05
 * @copyright:libo-alex4java
 * @email:liboware@gmail.com
 * @description:
 * snowflake是Twitter开源的分布式ID生成算法，
 * 结果是一个long型的ID。其核心思想是：使用41bit作为毫秒数，10bit作为机器的ID
 * （5个bit是数据中心，5个bit的机器ID），
 * 12bit作为毫秒内的流水号（意味着每个节点在每毫秒可以产生
 * 4096 个 ID），最后还有一个符号位，永远是0
 *
 * <pre>snowflake id生成器算法实现</pre>
 * <b>
 *     核心代码为其IdWorker这个类实现，其原理结构如下，我分别用一个0表示一位，用—分割开部分的作用：
 *  * 1||0---0000000000 0000000000 0000000000 0000000000 0 --- 00000 ---00000 ---000000000000
 *  * 在上面的字符串中，第一位为未使用（实际上也可作为long的符号位），接下来的41位为毫秒级时间，
 *  * 然后5位datacenter标识位，5位机器ID（并不算标识符，实际是为线程标识），
 *  * 然后12位该毫秒内的当前毫秒内的计数，加起来刚好64位，为一个Long型。
 *  * 这样的好处是，整体上按照时间自增排序，并且整个分布式系统内不会产生ID碰撞（由datacenter和机器ID作区分），
 *  * 并且效率较高，经测试，snowflake每秒能够产生26万ID左右，完全满足需要。
 *  * <p>
 *  * 64位ID (42(毫秒)+5(机器ID)+5(业务编码)+12(重复累加))
 * </b>
 */
public class SnowflakeHolder {

    /**
     * 数据中心ID
     */
    private final long dataId;

    /**
     * 任务中心ID
     */
    private final long workId;

    /**
     * 上次生产id时间戳
     */
    private static long lastTimestamp = -1L;

    /**
     * 0，并发控制
     */
    private long sequence = 0L;

    /**
     * 构造器服务
     * @param dataId
     * @param workId
     */
    public SnowflakeHolder(long dataId, long workId) {
        if (workId > SnowflakeConfig.MAX_WORKER_ID || workId < 0) {
            throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", SnowflakeConfig.MAX_WORKER_ID));
        }
        if (dataId > SnowflakeConfig.MAX_DATA_CENTER_ID || dataId < 0) {
            throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", SnowflakeConfig.MAX_DATA_CENTER_ID));
        }
        this.workId = workId;
        this.dataId = dataId;
    }


    /**
     *
     * @return
     */
    public synchronized long nextId() {
        //校验操作时间戳
        long currentTimestamp =  Clock.systemUTC().millis();
        if(checkClockTimestamp(currentTimestamp)){
            throw new IllegalStateException("timestamp is wrong！");
        }else if(currentTimestamp == lastTimestamp){
            // 当前毫秒内，则+1
            sequence = (sequence + 1) & SnowflakeConfig.SEQUENCE_MASK;
            if (sequence == 0) {
                // 当前毫秒内计数满了，则等待下一秒
                while(currentTimestamp <= lastTimestamp){
                    currentTimestamp = Clock.systemUTC().millis();
                }
            }
        }else{
            sequence = 0L;
        }
        lastTimestamp = currentTimestamp;

        // ID偏移组合生成最终的ID，并返回ID
        long nextId = ((currentTimestamp - SnowflakeConfig.TWEPOCH) << SnowflakeConfig.TIMESTAMPLEFT_SHIFT)
                | (dataId << SnowflakeConfig.DATA_CENTERID_SHIFT)
                | (workId << SnowflakeConfig.WORKERID_SHIFT) | sequence;

        return nextId;
    }


    /**
     * 校验时间戳频率
     * @return
     */
    private boolean checkClockTimestamp(long timestamp){
        return timestamp < lastTimestamp;
    }


    /**
     * <p>
     * 获取 maxWorkerId
     * </p>
     */
    protected static long getMaxWorkerId(long datacenterId, long maxWorkerId) {
        StringBuffer mpid = new StringBuffer();
        mpid.append(datacenterId);
        String name = ManagementFactory.getRuntimeMXBean().getName();
        if (!name.isEmpty()) {
            /*
             * GET jvmPid
             */
            mpid.append(name.split("@")[0]);
        }
        /*
         * MAC + PID 的 hashcode 获取16个低位
         */
        return (mpid.toString().hashCode() & 0xffff) % (maxWorkerId + 1);
    }

    /**
     * <p>
     * 数据标识id部分
     * </p>
     */
    protected static long getDatacenterId(long maxDatacenterId) {
        long id = 0L;
        try {
            InetAddress ip = InetAddress.getLocalHost();
            NetworkInterface network = NetworkInterface.getByInetAddress(ip);
            if (network == null) {
                id = 1L;
            } else {
                byte[] mac = network.getHardwareAddress();
                id = ((0x000000FF & (long) mac[mac.length - 1])
                        | (0x0000FF00 & (((long) mac[mac.length - 2]) << 8))) >> 6;
                id = id % (maxDatacenterId + 1);
            }
        } catch (Exception e) {
            System.out.println(" getDatacenterId: " + e.getMessage());
        }
        return id;
    }


    public static void main(String[] args){
        System.out.println(Long.toBinaryString(1161815962433880064L));
        System.out.println("1161815962433880064".length());
    }

}
